Ext.onReady(function(){

    /*var today = new Date();
    currYear  = today.getFullYear();*/

    var years = [];
    /*years.push([currYear]);
    years.push([currYear-1]);
    years.push([currYear+1]);*/

    var columnRenderer = function(value){
        var combo = this.editor
        var r = combo.findRecord(combo.valueField, value);
        return r ? r.get(combo.displayField) : combo.valueNotFoundText;
    }

    var dateColumnRenderer =  function(value){
        //alert(value);
        //alert(typeof(value instanceof Date));
        /*if (typeof(value) == 'string'){
            var dmyDate = new Array();
            dmyDate = value.split('-');
            var date = dmyDate[2]+'/'+dmyDate[1]+'/'+dmyDate[0];
            return date;
        }
        else{
            return value;
        }*/
        /*if(typeof(value) == 'string'){
            var dmyDate = new Array();
            dmyDate = value.split('-');
            value = new Date(dmyDate[0]+' '+dmyDate[1]+' '+dmyDate[2]).format('d/m/Y');
            return value;
        }
        else if(value != undefined){
            return value.format('d/m/Y');
        }
        return value;*/
        //alert(value instanceof Date);
        /*if(value != undefined){
            return value.format('d/m/Y');
        }
        return value;*/
        if (!value)                return '';
        //if (value instanceof Date) return value.format('d/m/Y');
        if (value instanceof Date) {
            value = value.format('d/m/Y');
            return value;
        }

        /*try{
            return Date.parseDate(value, 'Y-m-d').format('d/m/Y');
        }catch(e){try{
            return Date.parseDate(value, 'Y-m-d H:i:s').format('d/m/Y');
        }catch(e){
            X.msg.FailureJs(e.message);
        }}*/
        try{
            value = Date.parseDate(value, 'Y-m-d').format('d/m/Y');
            return value;
        }catch(e){try{
            value = Date.parseDate(value, 'Y-m-d H:i:s').format('d/m/Y')
            return value;
        }catch(e){
            X.msg.FailureJs(e.message);
        }}
    }

        var hourColumnRenderer =  function(value){
            //var strDate = value.date;
            /*alert(value.slice(0,5));
            alert(typeof(value));
            return;
            var date = new Date(Date.parse(strDate.replace(/-/g, " ")));*/
            /*if(value != undefined){
                return value.slice(0,5);
            }
            return value;*/
            if(typeof(value) == 'string'){
                var timeDate = new Date().toDateString()+' '+value.slice(0,5);
                value = new Date(timeDate).format('H:i');
                return value;
            }
            return value;
        }

    var h_editar_success = function(obj){
        X.get('editWindow').close();
        window.location = '/calendario';
    }

    /*X.sStore({
      id     : 'yearStore',
      fields : ['years'],
      data   : years
    });*/

    X.aStore({
        id     : 'tipoStore',
        fields : [ 'idTipo','nombre' ],
        data   : [ [1,'Vacaciones'],[2,'Suspensión'],[3,'Asueto/Feriado'] ]
    });

    X.store({
        id     : 'editStore',
        //url    : '/calendario/ajax-editar',
        fields : [ 'idCalendario', 'descripcion', 'fechaInicio', 'fechaFin',
                   'horaInicio', 'horaFin', 'tipo', 'carrera', 'semestres' ]
        /*fields : [ 'idCalendario', 'descripcion', {name:'fechaInicio', type:'date', dateFormat:'d/m/Y'},
                   {name:'fechaFin', type:'date'},'horaInicio','horaFin', 'tipo', 'carrera', 'semestres' ]*/
    });

    X.store({
        id     : 'storeEditarCarrera',
        fields : ['idCarrera', 'nombre']
    });

    var colModel = new Ext.grid.ColumnModel({
        defaults: {
            menuDisabled: true
        },
        columns: [
            {header: 'Fecha inicial', dataIndex: 'fechaInicio', width : 85,
                                  editor: new X.form.date ({id:'inicio'}),
                                  renderer: dateColumnRenderer
            },
            {header: 'Fecha final', dataIndex: 'fechaFin', width : 85,
                                  editor: new X.form.date ({id:'fin'}),
                                  renderer: dateColumnRenderer
            },
            {
              header: 'Desde', dataIndex: 'horaInicio', width : 55,
              editor: new X.form.time({
                          minValue : '0:00 AM',
                          maxValue : '11:59 PM',
                          format   : 'H:i',
                          increment: 30,
                          listWidth: 55
                      })/*,
                      renderer: hourColumnRenderer*/
            },
            {
              header: 'Hasta', dataIndex: 'horaFin', width : 55,
              editor: new X.form.time({
                          minValue : '0:00 AM',
                          maxValue : '11:59 PM',
                          format   : 'H:i',
                          increment: 30,
                          listWidth: 55
                      })/*,
                      renderer: hourColumnRenderer*/
            },
            {header: 'Carrera', dataIndex: 'carrera', width : 135,
                                  editor: new X.form.combo({
                                              dfield  :'nombre',
                                              vfield  :'idCarrera',
                                              storeId :'storeEditarCarrera'
                                          }),
                                  renderer: columnRenderer
            },
            {header: 'Semestres', dataIndex: 'semestres', width : 100,
                                      editor: new X.form.text({
                                                  id:'semestre',
                                                  width:230,
                                                  maxlen: 35
                                              })
            },
            {header: 'Tipo', dataIndex: 'tipo', width : 100,
                                  editor: new X.form.combo({
                                              dfield  :'nombre',
                                              vfield  :'idTipo',
                                              storeId :'tipoStore'
                                          }),
                                  renderer: columnRenderer
            },
            {header: 'Descripción', dataIndex: 'descripcion', width : 170,
                                      editor: new X.form.text({
                                                  id:'descripcion',
                                                  width:230,
                                                  maxlen: 35
                                              })
            }
        ]
    });

    X.grid.editor({
        id          : 'editGrid',
        height      : 261,
        width       : 804,
        cm          : colModel,
        storeId     : 'editStore',
        x           : 10,
        y           : 45,
        tbar : new Ext.Toolbar({
            items:[
                X.form.button({text:'Agregar', id:'editAddDetalle', icon:'/img/icon_agregar.png'
                }),'-',
                X.form.button({text:'Eliminar', id:'editRemDetalle', icon:'/img/icon_eliminar.png'})
            ]
        })
    });

    X.get('inicio').addListener('focus', function(){
        var anho = X.get('editAnho').value;
        var newMin = new Date('01/01/'+anho);
        var newMax = new Date('12/31/'+anho);
        this.setMinValue(newMin);
        this.setMaxValue(newMax);
    });

    X.get('fin').addListener('focus', function(){
        var anho = X.get('editAnho').value;
        var newMin = new Date('01/01/'+anho);
        var newMax = new Date('12/31/'+anho);
        this.setMinValue(newMin);
        this.setMaxValue(newMax);
    });

    X.event.button('editAddDetalle', function(){
        var grid = X.get('editGrid');
        grid.stopEditing();
        grid.store.insert(0, new grid.store.recordType({}));
        grid.startEditing(0,0);
        grid.getSelectionModel().selectRow(0);
   });

   X.event.button('editRemDetalle', function(){
       var grid = X.get('editGrid');
       var record = grid.getSelectionModel().getSelected();
       if (record) {
           var index = grid.store.indexOf(record);
           grid.store.removeAt(index);
           if (index < grid.store.getCount())
               grid.getSelectionModel().selectRow(index);
           else
               grid.getSelectionModel().selectRow(index-1);
        }
   });

    X.form.panel({
        id     : 'editForm',
        height : 363,
        width  : 836,
        items  : [
            X.form.label  ({x:10,  y:16,  text:'Año:'}),
            X.form.combo  ({x:50, y:8, width:60,  id:'editAnho',
                                                  dfield:'years',
                                                  vfield:'years',
                                                  storeId:'yearStore'
                                                  }),
            X.form.hidden ({id:'editorRows'}),
            X.form.button ({x:644, y:320, width:80, id:'editCargar',  text:'Guardar'}),
            X.form.button ({x:734, y:320, width:80, id:'editCancelar',  text:'Cancelar'}),
            X.get('editGrid')
        ]
    });

   X.event.button('editCargar', function(){

        var store = X.get('editStore');
        var rowCount = store.getCount();

        if (rowCount<=0){
            X.msg.failure('Debe agregar al menos una fecha al calendario');
        }
        else{
            //Control de campo obligatorios en detalles del calendario
            var grid = X.get('editGrid');
            var emptyField = false;
            for (var i=0; i<rowCount; i++){
                var record = store.getAt(i);
                //alert(record.get('fechaInicio'));
                //alert(record.get('fechaFin'));
                if(Ext.isEmpty(record.get('fechaInicio'))){
                    grid.getSelectionModel().selectRow(i);
                    emptyField = true;
                    X.msg.failure('Debe completar el campo <b>Fecha inicial</b> en la fila '+(i+1)+'.');
                }else if(Ext.isEmpty(record.get('fechaFin'))){
                    grid.getSelectionModel().selectRow(i);
                    emptyField = true;
                    X.msg.failure('Debe completar el campo <b>Fecha final</b> en la fila '+(i+1)+'.');
                }else if(Ext.isEmpty(record.get('horaInicio'))){
                    grid.getSelectionModel().selectRow(i);
                    emptyField = true;
                    X.msg.failure('Debe completar el campo <b>Desde</b> en la fila '+(i+1)+'.');
                }else if(Ext.isEmpty(record.get('horaFin'))){
                    grid.getSelectionModel().selectRow(i);
                    emptyField = true;
                    X.msg.failure('Debe completar el campo <b>Hasta</b> en la fila '+(i+1)+'.');
                }else if(Ext.isEmpty(record.get('carrera'))){
                    grid.getSelectionModel().selectRow(i);
                    emptyField = true;
                    X.msg.failure('Debe completar el campo <b>Carrera</b> en la fila '+(i+1)+'.');
                }else if(Ext.isEmpty(record.get('semestres'))){
                    grid.getSelectionModel().selectRow(i);
                    emptyField = true;
                    X.msg.failure('Debe completar el campo <b>Semestres</b> en la fila '+(i+1)+'.');
                }else if(Ext.isEmpty(record.get('tipo'))){
                    grid.getSelectionModel().selectRow(i);
                    emptyField = true;
                    X.msg.failure('Debe completar el campo <b>Tipo</b> en la fila '+(i+1)+'.');
                }else if(Ext.isEmpty(record.get('descripcion'))){
                    grid.getSelectionModel().selectRow(i);
                    emptyField = true;
                    X.msg.failure('Debe completar el campo <b>Descripción</b> en la fila '+(i+1)+'.');
                }
            }

            if(!emptyField){

                grid.getSelectionModel().selectAll();
                var sm = grid.getSelectionModel().getSelections();
                var detail = new Array();
                for (i=0; i<=sm.length-1; i++) {
                    var data = {idCalendario:'', fechaInicio:'',fechaFin:'',horaInicio:'',horaFin:'',
                                carrera:'',semestres:'',tipo:'',descripcion:''};
                    data.idCalendario=sm[i].get('idCalendario')
                    data.fechaInicio=sm[i].get('fechaInicio');//.format('d/m/Y');
                    data.fechaFin=sm[i].get('fechaFin');//.format('d/m/Y');
                    data.horaInicio=sm[i].get('horaInicio');
                    data.horaFin=sm[i].get('horaFin');
                    data.carrera=sm[i].get('carrera');
                    data.semestres=sm[i].get('semestres');
                    data.tipo=sm[i].get('tipo');
                    data.descripcion=sm[i].get('descripcion');
                    detail.push(data);
                    //alert(detail.toSource()+' '+data.toSource())
                    delete data;
                    data = {};
                }

                X.ajax({
                    url: '/calendario/ajax-editar',
                    params: {
                        anho: X.value('editAnho'),
                        detalles: Ext.encode(detail)
                    },
                    afterSuccess:h_editar_success
                });

            }else{
                return;
            }
        }
    });

    X.event.button('editCancelar', function(){
        X.get('editWindow').close();
        window.location = '/calendario'
    });

        // WINDOW
    X.win.panel({
        id    : 'editWindow',
        //defaultButton : 'editUsername',
        //resizable: false,
        //items         : X.get('editForm')
        title : 'Editar calendario',
        modal : false,
        items : X.get('editForm')

    });

    X.get('editWindow').begin = function(){
        // el if para asegurar abrir una sola ventana (aunque sea modal)
        if (X.get('editWindow').isVisible()==false){
            X.show('editWindow');
        }
    }

});